import { IOSuper } from './super.js'

export class Keyboard extends IOSuper {
  constructor() {
    super();
  }

  keydown(e) {
    this.backupNowState();
    if (e.key === "ArrowLeft") {
      this.setNowState('left', true);
    } else if (e.key === "ArrowRight") {
      this.setNowState('right', true);
    } else if (e.key === "a") {
      this.setNowState('a', true);
    } else if (e.key === "d") {
      this.setNowState('d', true);
    } else if (e.key === 'ArrowUp') {
      this.setNowState('up', true);
    } else if (e.key === 'ArrowDown') {
      this.setNowState('down', true);
    }
    
    this.execTrigger();
  }

  keyup(e) {
    this.backupNowState();
    if (e.key === "ArrowLeft") {
      this.setNowState('left', false);
    } else if (e.key === "ArrowRight") {
      this.setNowState('right', false);
    } else if (e.key === "a") {
      this.setNowState('a', false);
    } else if (e.key === 'd') {
      this.setNowState('d', false);
    } else if (e.key === 'ArrowUp') {
      this.setNowState('up', false);
    } else if (e.key === 'ArrowDown') {
      this.setNowState('down', false);
    }
  
    this.execTrigger();
  }

  init() {
    window.addEventListener("keydown", this.keydown.bind(this));
    window.addEventListener("keyup", this.keyup.bind(this));
  }

  destroy() {
    window.removeEventListener('keydown', this.keydown);
    window.removeEventListener('keyup', this.keyup);
    this.initNowState();
    this.clearTriggers();
  }
}